 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : WebQQCore
 * Package  : iqq.im.protocol
 * File     : CheckVerifyAction.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : 2012-9-1
 * License  : Apache License 2.0 
 */
package com.windmill.action;

import iqq.im.QQActionListener;
import iqq.im.QQException.QQErrorCode;
import iqq.im.action.AbstractHttpAction;
import iqq.im.core.QQService;
import iqq.im.event.QQActionEvent;
import iqq.im.http.QQHttpRequest;
import iqq.im.http.QQHttpResponse;
import iqq.im.service.HttpService;
import iqq.im.util.QQEncryptor;

import java.io.StringReader;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.windmill.bean.SlotCard;
import com.windmill.bean.Stove;
import com.windmill.bean.UserMainCardInfo;
import com.windmill.core.MargicCardClient;
import com.windmill.util.XMLUtils;

/**
 *获取魔卡卡片V3版本所有信息
 *
 */
public class GetUserMainCardInfoAction extends AbstractHttpAction {
	private MargicCardClient client;
	private String qq;
	public GetUserMainCardInfoAction(String qq, MargicCardClient context, QQActionListener listener) {
		super(context, listener);
		this.client = context;
		this.qq = qq;
	}

	@Override
	public QQHttpRequest buildRequest() {
		HttpService httpService = (HttpService) getContext().getSerivce(QQService.Type.HTTP);		
		String gtk = QQEncryptor.gtk(httpService.getCookie("skey",null).getValue());
		QQHttpRequest req = createHttpRequest("POST","http://card.show.qq.com/cgi-bin/card_user_mainpage?g_tk="+gtk);
		req.addHeader("Content-Type", "application/x-www-form-urlencoded");
		req.removeHeader("Referer");
		req.addPostValue("code", "");
		req.addPostValue("uin", getContext().getAccount().getQQ()+"");
		req.addPostValue("opuin", qq);
		return req;
	}	

	@Override
	public void onHttpStatusOK(QQHttpResponse response) {
		try {
			JSONObject userInfo = new JSONObject(XMLUtils.parseMainPageXml(new StringReader(response.getResponseString())));
			UserMainCardInfo mainCardInfo = parseUserMainCardInfo(userInfo);				
			notifyActionEvent(QQActionEvent.Type.EVT_OK,mainCardInfo);
		} catch (Exception e) {
			System.out.println("解释mainCardInfo 错误。");
			notifyActionEvent(QQActionEvent.Type.EVT_ERROR, QQErrorCode.UNEXPECTED_RESPONSE);
		}        
	}
	
	@SuppressWarnings("rawtypes")
	private UserMainCardInfo parseUserMainCardInfo(JSONObject jsonObject) throws JSONException {
		UserMainCardInfo main = null;
		if(jsonObject.getInt("code")==0){
			main = new UserMainCardInfo();
			Map m = (Map) jsonObject.get("user");
			JSONObject obj = new JSONObject(m);
			main.setQq(obj.getLong("uin"));
			main.setSex(obj.getInt("sex"));
			main.setName(obj.getString("nick"));
			main.setElfname(obj.getString("elfname"));
			main.setRedvip(obj.getInt("redvip"));
			main.setRedlv(obj.getInt("redlv"));
			main.setYearvip(obj.getInt("yearvip"));
			main.setLv(obj.getInt("lv"));
			main.setMoney(obj.getInt("money"));
			main.setExp(obj.getInt("exp"));
			main.setMana(obj.getInt("mana"));
			main.setRandchance(obj.getInt("randchance"));
			main.setLastrandti(obj.getLong("lastrandti"));
			main.setRegti(obj.getLong("regti"));
			m = (Map) jsonObject.get("changebox");
			obj = new JSONObject(m);
			main.setChangeBoxSize(obj.getInt("cur"));
			String[] themeIds = obj.getString("exch").split(",");
			for(String id:themeIds){
				if(!"0".equals(id)){
					main.addChangeThemes(client.getCardStore().getThemeById(Integer.valueOf(id)));
				}
			}
			m = (Map) jsonObject.get("storebox");
			obj = new JSONObject(m);
			main.setStoreBoxSize(obj.getInt("cur"));
			List list = (List) jsonObject.get("stoveboxcards");
			JSONArray array = new JSONArray(list);
			parseStove(main,array);
			list = (List) jsonObject.get("changeboxcards");
			array = new JSONArray(list);
			parseSoltCard(main,array);
			list = (List) jsonObject.get("storeboxcards");
			array = new JSONArray(list);
			parseSoltCard(main,array);
		}
		return main;
	}

	@SuppressWarnings("rawtypes")
	private void parseStove(UserMainCardInfo main, JSONArray array) throws JSONException {
		for(int i=0;i<array.length();i++){
			Map m = (Map) array.get(i);
			JSONObject obj = new JSONObject(m);
			Stove stove = new Stove();
			if(obj.getInt("id")!=0)	stove.setCard(client.getCardStore().getCardById(obj.getInt("id")));
			if(m.get("id2")!=null&&obj.getInt("id2")!=0)	stove.setCard2(client.getCardStore().getCardById(obj.getInt("id2")));
			stove.setStove(obj.getInt("stove"));
			stove.setFlag(obj.getInt("flag"));
			stove.setLocktime(obj.getLong("locktime"));
			stove.setProp(obj.getInt("prop"));
			stove.setBtime(obj.getLong("btime"));
			stove.setType(obj.getInt("type"));
			stove.setSlot(obj.getInt("slot"));
			if(m.get("slottype")!=null)
				stove.setSlottype(obj.getString("slottype"));
			if(m.get("opuin")!=null) 
				stove.setOpuin(obj.getLong("opuin"));
			if(m.get("opuin2")!=null)
				stove.setOpuin2(obj.getLong("opuin2"));
			main.addStoveBoxCard(stove);
		}
	}

	@SuppressWarnings("rawtypes")
	private void parseSoltCard(UserMainCardInfo main, JSONArray array) throws JSONException {
		for(int i=0;i<array.length();i++){
			Map m = (Map) array.get(i);
			JSONObject obj =  new JSONObject(m);
			//{id=5027, unlock=0, status=0, st=0, type=1, slot=1}, 
			//{id=1394, status=0, st=0, type=1, slot=0}
			SlotCard slotCard = new SlotCard();
			if(obj.getInt("id")!=0){
				slotCard.setCard(client.getCardStore().getCardById(obj.getInt("id")));
				slotCard.setStatus(obj.getInt("status"));
				slotCard.setSt(obj.getInt("st"));
				slotCard.setType(obj.getInt("type"));
				slotCard.setSlot(obj.getInt("slot"));
				if(m.get("unlock")!=null&&slotCard.getCard()!=null){
					slotCard.setUnlock(obj.getInt("unlock"));
					main.addChangeBoxCard(slotCard);
				}else{
					main.addStoreBoxCard(slotCard);
				}
			}
		}
	}



}
